// 引入SDK核心类
var QQMapWX = require('../../qqmap-wx-jssdk.min.js');

var qqmapsdk = new QQMapWX({
  key: '6FTBZ-OPECR-OYVWT-WULAV-V7VPQ-FAFCT' // 必填
});

var util = require('../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    /*activity*/
    item:0,
    tab:0,

    /*undone*/ 
    label:'',
    typeItems:[
        {name:'代购物品',selected:false},
        {name:'家政服务',selected:false},
        {name:'健康指导',selected:false},
        {name:'谈心交流',selected:false},
        {name:'陪伴娱乐',selected:false},
        {name:'其他类型',selected:false}],
    /*未完成服务 */
    undone_list:[],

    doinghidden:true,
    volserhidden:true,
    serhidden:true,

    /*老人个人服务*/
    old_list:{},

    /*doing 进行中服务 老人或志愿者*/
    doing_list:{},
    longitude:null,
    latitude:null,
    /*服务对象信息 或 志愿者信息 */
    targetlist:{},

    oldhidden:'',
    volhidden:'',
    changeneed:false,
    changetxt:'',
    

    nowtime:'',
    nursingspace:'九江泰康养老院',
    
    hiddenname:true, 
    percent:'',

    //reviewed 待审核服务
    checklist:[],
    checkcollist:[],
    number:'',
    volname:'',

    //done 已完成服务
   reviewed_list:[],
  },

  onShow:function(){
    if(!(wx.getStorageSync('userInfo'))||wx.getStorageSync('identity') === ''){
      wx.showToast({
        icon:'none',
        title: '登录后使用',
      })
      wx.switchTab({
        url: '/pages/person/person',
      })
    }

    if(wx.getStorageSync('identity') == 'old'){
      this.setData({
        oldhidden:false,
        volhidden:true
      })
    }else{
      this.setData({
        oldhidden:true,
        volhidden:false
      })
    }


  },

  onLoad:function(){
  
    var that = this
    wx.request({
      url: 'http://127.0.0.1:8082/demo1/superadmin/listser',
      method:'GET',
      data:{},
      success:(res)=>{
        var serList = res.data.serList
        console.log(res.data.serList)
        var len = serList.length

        var arr1 = []
        var arr2 = []
        var arr3 = []
        for(var i = 0;i<len;i++){
          if(serList[i].serstate === '未完成'){
            if(serList[i].seroldid == wx.getStorageSync('openid')){
              that.data.old_list = serList[i]
              that.setData({
                serhidden:false
              })
            }
              serList[i].selected = false
              arr1.unshift(serList[i])
          }

          if(serList[i].serstate === '进行中' && (serList[i].servolid == wx.getStorageSync('openid') || 
          serList[i].seroldid == wx.getStorageSync('openid'))){
            
            if(wx.getStorageSync('identity') == 'vol'){
              wx.request({
                url: 'http://127.0.0.1:8082/demo1/superadmin/getolderbyid',
                data:{'olderId':serList[i].seroldid},
                success:(res)=>{
                  console.log(res);
                  that.data.targetlist = res.data.older
                  that.setData({
                    volserhidden:false,
                    targetlist:that.data.targetlist
                  })
                  this.getloc()
                }
              })
            }
            if(wx.getStorageSync('identity') == 'old'){
              wx.request({
                url: 'http://127.0.0.1:8082/demo1/superadmin/getvolunteerbyid',
                data:{'volunteerId':serList[i].servolid},
                success:(res)=>{
                  // console.log(res)
                  that.data.targetlist = res.data.volunteer
                  if(that.data.targetlist.address == null)
                    that.data.targetlist.address = '无' 
                  that.setData({
                    doinghidden:false,
                    targetlist:that.data.targetlist
                  })
                }
              })
            }
            that.data.doing_list = serList[i]
          }

          if(serList[i].serstate === '审核中' && (serList[i].servolid == wx.getStorageSync('openid') || 
              serList[i].seroldid == wx.getStorageSync('openid'))){

                if(wx.getStorageSync('identity') == 'old'){
                  wx.request({
                    url: 'http://127.0.0.1:8082/demo1/superadmin/getvolunteerbyid',
                    data:{'volunteerId':serList[i].servolid},
                    success:(res)=>{
                      // console.log(res)
                      var number = res.data.volunteer.phone
                      var volname = res.data.volunteer.volname
                      that.setData({
                        number:number,
                        volname:volname
                      })
                    }
                  })
                }
              serList[i].number = that.data.number
              serList[i].volname = that.data.volname
             
              arr2.unshift(serList[i]) 
              
          }

          if(serList[i].serstate === '已完成' && (serList[i].servolid == wx.getStorageSync('openid') || 
            serList[i].seroldid == wx.getStorageSync('openid'))){
              if(serList[i].judgelevel == null){
                serList[i].not_judge = false
              }else{
                serList[i].not_judge = true
              }
              // console.log(serList[i])
              arr3.unshift(serList[i])
          }
        }
        
        that.setData({
          undone_list:arr1,
          doing_list:that.data.doing_list,
          checklist:arr2,
          reviewed_list:arr3,
          old_list:this.data.old_list
        })
      //  console.log(this.data.undone_list)
      //  console.log(this.data.doing_list)
      //  console.log(this.data.checklist)
      //  console.log(this.data.reviewed_list)
      // console.log(this.data.old_list)
        

    /*进行中的服务进度*/
    var nowdate = util.formatTime(new Date());
    this.setData({
      nowtime:nowdate
    })
    // console.log(this.data.nowtime)
    //获取到的时间
    // var nowTime = '2018-09-11 13:50:52';
    var doinglist = this.data.doing_list 
    var len = Object.keys(doinglist).length
    if(len != 0 && wx.getStorageSync('identity') == 'vol'){
      var startTime = doinglist.starttime;
      var finishTime = doinglist.finishtime;
      var nowTime = this.data.nowtime;
      // console.log(nowTime)
       var thisTime1 = startTime;
      var thisTime2 = nowTime;
      var thisTime3 = finishTime;
      thisTime1 = thisTime1.replace(/-/g, '/');
      thisTime2 = thisTime2.replace(/-/g, '/');
      thisTime3 = thisTime3.replace(/-/g, '/');
      var time1 = new Date(thisTime1);
      var time2 = new Date(thisTime2);
      var time3 = new Date(thisTime3);
      time1 = time1.getTime();
      time2 = time2.getTime();
      time3 = time3.getTime();
      // console.log(time1,time2,time3);
      var allTimtime = time3 - time1;
      var delTime = time2 - time1;
      if(delTime<allTimtime){
        // console.log(allTimtime,delTime);
        var percent = parseInt(100*(delTime / allTimtime));
        this.setData({
          percent:percent
        })
      }else{
        this.setData({
          percent:100
        })
        var arrt={
          serid:this.data.doing_list.serid,
          serstate:'审核中'
        }
        wx.request({
          url: 'http://127.0.0.1:8082/demo1/superadmin/updateserstateonly',
          data:JSON.stringify(arrt),
          method:'POST',
          success:(res)=>{
            console.log(res)
            that.setData({
              volserhidden:true
            })
            
          }
        })
      }
    }
    
    
    /*服务时长 */
    var len = this.data.checklist.length;
    if(len != 0){
      var checklist = this.data.checklist;
      // console.log(len)
      for(var i=0;i<len;i++){
      
        var start = checklist[i].starttime.replace(/-/g, '/');
        var finish = checklist[i].finishtime.replace(/-/g, '/');
        var start1 = new Date(start);
        var finish1 = new Date(finish);
        var start2 = start1.getTime();
        var finish2 = finish1.getTime();
        var hour = parseInt((finish2-start2)/1000/60/60)
        // console.log(start2,finish2,hour)
        var rhour = 'checklist['+i+'].hour';
        var rcoin = 'checklist['+i+'].coin';
        this.setData({
           [rhour]: hour,
           [rcoin]: (hour*2)
        })
      }
    }
    

    /*服务时长 */
    var len = this.data.reviewed_list.length;
    if(len != 0){
      var reviewedlist = this.data.reviewed_list;
    // console.log(len)
    for(var i=0;i<len;i++){
      var start = reviewedlist[i].starttime.replace(/-/g, '/');
      var finish = reviewedlist[i].finishtime.replace(/-/g, '/');
      var start1 = new Date(start);
      var finish1 = new Date(finish);
      var start2 = start1.getTime();
      var finish2 = finish1.getTime();
      var hour = parseInt((finish2-start2)/1000/60/60)
      // console.log(start2,finish2,hour)
      var chour = 'reviewed_list['+i+'].hour';
      var ccoin = 'reviewed_list['+i+'].coin';
      this.setData({
         [chour]: hour,
         [ccoin]: (hour*2)
      })
    }
    }

    }
    })

  },

  //地标
  getloc:function(){
    var _this = this;
    //调用地址解析接口[]

    if(this.data.volserhidden == false){
      qqmapsdk.geocoder({
        //获取表单传入地址
        address: _this.data.doing_list.seraddress, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
        success: function(res) {//成功后的回调
          // console.log(res);
          var res = res.result;
          var latitude = res.location.lat;
          var longitude = res.location.lng;
          //根据地址解析在地图上标记解析地址位置
          _this.setData({ // 获取返回结果，放到markers及poi中，并在地图展示
            markers: [{
              id: 0,
              title: res.title,
              latitude: latitude,
              longitude: longitude,
              iconPath: '/static/image/地图-地标.png',//图标路径
              width: 30,
              height: 30,
              // callout: { //可根据需求是否展示经纬度
              //   content: latitude + ',' + longitude,
              //   color: '#000',
              //   display: 'ALWAYS'
              // }
            }],
            poi: { //根据自己data数据设置相应的地图中心坐标变量名称
              latitude: latitude,
              longitude: longitude
            },
            latitude:latitude,
            longitude:longitude
          });
        },
        fail: function(error) {
          console.error(error);
        },
        complete: function(res) {
          console.log(res);
        }
      })
    }
    
  },

  /*activity*/
  changeItem:function(e){
    this.setData({
      item:e.target.dataset.item
    })
  },
  
  changeTab:function(e){
    this.setData({
       tab:e.detail.current
    })
  },

  /*undonevol*/
  sreenShow:function(){
    this.setData({
      sreenShow:!this.data.sreenShow
    })
  },
  /*重置筛选 */
  cancel:function(){
    this.setData({
      sreenShow:false
    })
    var len =this.data.typeItems.length;
    for(var i=0;i<len;i++){ 
      this.data.typeItems[i].selected = false
    }
    var len = this.data.undone_list.length
    for(var i=0;i<len;i++){
      this.data.undone_list[i].selected = false;
    }
    this.setData({
      typeItems:this.data.typeItems,
      undone_list:this.data.undone_list
    })
  },
  /*选择服务类型 */
  chooseitem:function(e){
    var len =this.data.typeItems.length;
    // console.log(e.currentTarget.dataset.index)
    var index = e.currentTarget.dataset.index;
    for(var i=0;i<len;i++){
      if(i!=index)
        this.data.typeItems[i].selected = false
    }
    this.data.typeItems[index].selected = !this.data.typeItems[index].selected;
    if(index === this.data.label){
      index = '' 
    }
    this.setData({
      label:index,
      typeItems:this.data.typeItems
    })
  },
/*确认筛选服务 */
  confirm:function(){
     var len = this.data.undone_list.length
    this.setData({
      sreenShow:false
    })
    // console.log(this.data.label)
    console.log(this.data.label)
    if(this.data.label === ''){
      for(var i=0;i<len;i++){
        this.data.undone_list[i].selected = false
      }
    }else{
      var label = this.data.typeItems[this.data.label].name

      if(label == ""){
        this.setData({
          sreenShow:false
        })
        for(var i=0;i<len;i++){
            this.data.undone_list[i].selected = false
          }
        
      }else{
        for(var i=0;i<len;i++){
          this.data.undone_list[i].selected = false
        }
          for(var i=0;i<len;i++){
            if(this.data.undone_list[i].label != label){
              this.data.undone_list[i].selected = true
            }
          }
      }
    }
    this.setData({
          undone_list:this.data.undone_list  
        })
  },

  /*跳转服务详情*/
  searchdetail:function(e){
    var num = e.currentTarget.dataset.index
    console.log(this.data.undone_list[num])
    wx.navigateTo({
      url: '/pages/activity_info/activity_info?undone_list='+JSON.stringify(this.data.undone_list[num])+
      '&doinglist='+JSON.stringify(this.data.doing_list),
    })
  },

/*undo old */
  create_new:function(){
   var len =this.data.serhidden
   console.log(len)
    if(len == false){
      wx.showToast({
        icon:'none',
        title: '已创建服务请求'
      })
    }else if(this.data.doinghidden == false){
      wx.showToast({
        icon:'none',
        title: '有服务正在进行',
      })
    }else{
        wx.navigateTo({
        url: '/pages/activity/service/service',
    })
    }
   
  },
  changeinfo:function(){
    var oldlist = JSON.stringify(this.data.old_list)
    console.log(oldlist)
    wx.navigateTo({
      url: '../changeinfo/changeinfo?oldlist='+oldlist,
    })
  },
  del:function(){
    var that  =this
  wx.showModal({
    title:'是否删除该服务',
    success:(res)=>{
      console.log(res)
      var serid = this.data.old_list.serid
      if(res.confirm){
        wx.request({
          url: 'http://127.0.0.1:8082/demo1/superadmin/deleteser',
          data:{'serid':serid},
          method:'POST',
          success:(res)=>{
            console.log(res)
            that.setData({
              serhidden:true  
            })
            that.onLoad()
          }
        })
     
      }
    }
  })
  },

  /*vol doing*/
  call:function(){ 
    // console.log(this.data.targetlist)
    wx.makePhoneCall({
      phoneNumber: this.data.targetlist.oldnumber,
    })
  },
  move:function(){
    console.log(this.data.longitude , this.data.latitude)
    wx.openLocation({
      // 上述方法 2 中获取到的经纬度
        latitude: this.data.latitude,
        longitude: this.data.longitude,
        scale: 28,
        name: this.data.address,  // 打开后显示的从WXML中传过来的地址名称
    })
  },
  show:function(e){
  console.log(this.data.hiddenname)
      this.setData({
        hiddenname:!this.data.hiddenname
      })

  },
  refresh:function(){
    this.onLoad()
    wx.showToast({
      title: '正在刷新...',
      icon: 'loading',
      mask: true,
      duration: 500
    })
     
  },
  /*old doing*/
  callvol:function(){
    wx.makePhoneCall({
      phoneNumber: this.data.targetlist.phone,
    })
  },
  change:function(){
    this.setData({
      changeneed:true,
      changetxt:this.data.doing_list.content
    })
  },
  changeneed:function(e){
    var t = e.detail.value
    this.setData({
      changetxt:t
    })
    
  },
  save:function(){
    this.setData({
      changeneed:false,
    })
    console.log(this.data.changetxt)
    var arrt = {
      serid:this.data.doing_list.serid,
      content:this.data.changetxt
    }
    wx.request({
      url: 'http://127.0.0.1:8082/demo1/superadmin/updatesercontent',
      data:JSON.stringify(arrt),
      method:'POST',
      success:(res)=>{
        console.log(res)
        this.onLoad()
      }
    })
  },
  shutservice:function(){
   wx.showModal({
     title:'是否终止该服务',
     success:(res)=>{
       if(res.confirm){
        var arrt={
          serid:this.data.doing_list.serid,
          serstate:'审核中'
        }
        wx.request({
          url: 'http://127.0.0.1:8082/demo1/superadmin/updateserstateonly',
          data:JSON.stringify(arrt),
          method:'POST',
          success:(res)=>{
            console.log(res)
            this.setData({
              doinghidden:true
            })
            this.onLoad()
          }
        })

          this.setData({
            doinghidden:true
          })
       }
     }
   })
  },
  /*reviewed*/
  /*done*/
  judge:function(e){
    var num = e.currentTarget.dataset.index
    var identity = wx.getStorageSync('identity')
    if(identity === 'vol' && this.data.reviewed_list[num].not_judge === false){
      wx.showToast({
        icon:'error',
        title: '志愿者无法评价',
      })
    }else if( identity === 'old' && this.data.reviewed_list[num].not_judge == false){
      var list = JSON.stringify(this.data.reviewed_list[num])
      wx.navigateTo({
      url: '../judge/judge?list='+list
    })
    }else if(this.data.reviewed_list[num].not_judge == true){
      // console.log(e)
      var judgelist = JSON.stringify(this.data.reviewed_list[num])
      // console.log(this.data.reviewed_list[num])
      wx.navigateTo({
        url: '/pages/judgeinfo/judgeinfo?judgelist='+judgelist,
      })
    }else{
      wx.showToast({
        title: '已评价',
      })
    }
    }
  
  
})